package com.hat.easyexcel_export.excel;

import com.alibaba.excel.write.handler.RowWriteHandler;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.metadata.holder.WriteTableHolder;
import org.apache.poi.ss.usermodel.*;

/**
 * @Description 自增序号拦截器
 * @author HuangAnting
 * @date 2022/4/12 17:27
*/
public class IndexRowWriteHandler implements RowWriteHandler {
    private static final String FIRST_CELL_NAME = "序号";
    /**
     * 序号的样式，与其他列保持一样的样式
     */
    private CellStyle firstCellStyle;
    private String description;
    /**
     * 列号
     */
    private int count = 0;
    public IndexRowWriteHandler(String description){
        this.description = description;
    }

    @Override
    public void afterRowDispose(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, Row row, Integer relativeRowIndex, Boolean isHead) {
        // 每一行首列单元格
        Cell indexCell = row.createCell(0);
        if(!isHead){
            indexCell.setCellValue(++count);
           try {
               row.getCell(3).setCellValue(description);
           }
           catch (Exception e){
           }
        }
        else {
            Workbook workbook = writeSheetHolder.getSheet().getWorkbook();
            firstCellStyle = firstCellStyle(workbook);
            indexCell.setCellValue(FIRST_CELL_NAME);
            indexCell.setCellStyle(firstCellStyle);
            writeSheetHolder.getSheet().setColumnWidth(0, 6 * 256);
        }
    }

    /**
     * excel首列序号列样式
     * @param workbook
     * @return
     */
    public  CellStyle firstCellStyle(Workbook workbook) {
        CellStyle cellStyle = workbook.createCellStyle();
        //居中
        cellStyle.setAlignment(HorizontalAlignment.CENTER);
        cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        // 灰色
        cellStyle.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
        //设置边框
        cellStyle.setBorderBottom(BorderStyle.THIN);
        cellStyle.setBorderLeft(BorderStyle.THIN);
        cellStyle.setBorderRight(BorderStyle.THIN);
        cellStyle.setBorderTop(BorderStyle.THIN);
        //文字
        Font font = workbook.createFont();
        font.setBold(Boolean.TRUE);
        cellStyle.setFont(font);
        return cellStyle;
    }
}
